<style rel="stylesheet/scss" lang="scss" scoped>
  @import "../../../styles/prod.scss";

  .mid {
    line-height: 140px;
  }
</style>
<template>
  <div class="app-container calendar-list-container">
    <!-- 基本属性 -->
    <template>
      <basic-form :basicInfo="basicForm" :ruleForm="detail" ref="basicForm" :lang="language"></basic-form>
    </template>
    <custom-card title="包含产品" class="mt-30">
      <template>
        <el-form inline>
          <el-form-item label="产品型号">
            <el-autocomplete v-model="proNo"
                             :fetch-suggestions="_searchProNo"
                             placeholder="请输入产品型号"
                             @select="selectPro"
            ></el-autocomplete>
            <!--<el-select v-model="proNo" placeholder="请选择" @change="selectPro">-->
            <!--<el-option v-for="(item, index) in proNoList"-->
            <!--:key="item.id"-->
            <!--:value="index"-->
            <!--:label="item.name"-->
            <!--:disabled="item.disabled">-->
            <!--</el-option>-->
            <!--</el-select>-->
          </el-form-item>
        </el-form>
        <el-table align="center" border fit highlight-current-row style="width: 100%" :data="detail.pdsCertProductsList"
                  v-if="showCertProductsList">
          <el-table-column type="index" label="序号" ></el-table-column>
          <!-- <el-table-column align="center" label="项目编号" prop="projectNo"></el-table-column> -->
          <el-table-column align="center" label="产品类型" prop="productCategory"></el-table-column>
          <el-table-column align="center" label="产品型号" prop="plmModelNo"></el-table-column>
          <el-table-column align="center" label="使用标准" v-if="false">
            <template slot-scope="scope">
              <el-select v-model="scope.row.certStandardId" placeholder="请选择">
                <el-option v-for="item in standardList" :key="item.id" :value="item.id" :label="item.name">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button type="danger" @click="delProject(scope.$index,scope.row.index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </custom-card>
    <custom-card title="证书文档" class="mt-30">
      <template>
        <upload-file btn-text="上传证书文档" @getFiles="getFiles"></upload-file>
        <el-table :data="detail.pdsCertFileList" border fit highlight-current-row style="width: 100%">
          <el-table-column align="center" label="文件名称" prop="fileName"></el-table-column>
          <!-- <el-table-column align="center" label="文件类型" prop="fileType"></el-table-column> -->
          <el-table-column align="center" label="文件大小">
            <template slot-scope="scope">
              {{scope.row.fileSize | showSize}}
            </template>
          </el-table-column>
          <el-table-column align="center" label="上传日期" prop="createTime"></el-table-column>
          <el-table-column align="center" label="备注">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" prop="">
            <template slot-scope="scope">
              <el-button @click="downloadFile">下载</el-button>
              <!-- <el-button type="danger" @click="delReport(scope.$index)">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </template>
    </custom-card>
    <custom-card title="报告" class="mt-30">
      <template>
        <el-button class="mt-30" @click="editReport('add')" type="primary">新增报告</el-button>
        <el-table :data="detail.pdsCertReportsDTOList" border fit highlight-current-row style="width: 100%">
          <el-table-column type="index"></el-table-column>
          <el-table-column align="center" label="报告编号" prop="certReportNo"></el-table-column>
          <el-table-column align="center" label="使用标准" prop="certStandard"></el-table-column>
          <el-table-column align="center" label="报告有效期" prop="certReportEffectiveDate"></el-table-column>
          <el-table-column align="center" label="操作" prop="">
            <template slot-scope="scope">
              <el-button @click="editReport(scope.$index)">编辑</el-button>
              <el-button type="danger" @click="delReport(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </custom-card>

    <div class="pds-btm mt-30">
      <!-- 已保存草稿
      <span class="tip">17分钟前</span> -->
      <div class="right">
        <el-button class="filter-item" type="default" @click="cancel()">取消</el-button>
        <el-button class="filter-item" type="warning" :disabled="loading" @click="validateForm(0)"
                   v-if="!isUpdate && !this.detail.status">保存草稿
        </el-button>
        <el-button class="filter-item" type="primary" :disabled="loading" @click="validateForm(1)">提交</el-button>
      </div>
    </div>

    <!-- 报告弹窗 -->
    <el-dialog title="报告详情" :visible.sync="reportDialog" width="80%">
      <el-form label-width="120px" label-suffix="：" :model="reportForm" ref="reportForm">
        <el-row>
          <el-col :span="8">
            <el-form-item label="报告编号" prop="certReportNo" required>
              <el-input v-model="reportForm.certReportNo" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="报告有效期" prop="certReportEffectiveDate" required>
              <el-date-picker v-model="reportForm.certReportEffectiveDate" placeholder="请选择" value-format="yyyy-MM-dd"
                              style="width: 100%"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预警阈值" required>
              <el-input v-model="reportForm.warningDay" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="使用标准" prop="certStandardId" required>
              <el-select v-model="reportForm.certStandardId" placeholder="请选择" style="width:100%;" @change="selectChange">
                <el-option v-for="item in standardList" :key="item.id" :value="item.id" :label="item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="相关参数" prop="params" required>
              <el-input v-model="reportForm.params" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="reportForm.remark" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <upload-list v-if="reportDialog" uploadFileId="upload-file" type="eipFile" btnText="上传报告文档"
                   v-model="reportForm.pdsCertReportFileList"></upload-list>

      <custom-card title="CDF" class="mt-30">
        <template>
          <el-button class="mt-30" @click="editCdf('add')" type="primary">新增CDF</el-button>
          <el-table :data="reportForm.pdsCertCdfsDTOList" border fit highlight-current-row style="width: 100%">
            <el-table-column type="index"></el-table-column>
            <el-table-column align="center" label="备注" prop="remark"></el-table-column>
            <el-table-column align="center" label="操作" prop="">
            <template slot-scope="scope">
                <el-button @click="editCdf(scope.$index)">编辑</el-button>
                <el-button type="danger" @click="delCdf(scope.$index)">删除</el-button>
                </template>
            </el-table-column>
          </el-table>
        </template>
      </custom-card>

      <span slot="footer" class="dialog-footer">
        <el-button @click="reportDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmReport">确 定</el-button>
      </span>
    </el-dialog>

    <!-- cdf弹窗 -->
    <el-dialog title="CDF详情" :visible.sync="cdfDialog" width="80%">
      <el-form label-width="120px" label-suffix="：" :model="cdfForm">
        <el-form-item label="报告编号">
          <el-input :value="reportForm.certReportNo" readonly></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="cdfForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <upload-list v-if="cdfDialog" uploadFileId="upload-file" type="eipFile" btnText="上传文档"
                   v-model="cdfForm.pdsCertCdfFilesList"></upload-list>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cdfDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmCdf">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
  import {
    mapGetters
  } from 'vuex';
  import * as baseApi from '@/api/common/index'
  import * as prodApi from '@/api/product/index'
  import * as certApi from '@/api/cert/index'
  import * as listApi from '@/api/cert/list/index'
  import BasicForm from '@/components/BasicForm/index'
  import CustomCard from '@/components/CustomCard/index'
  import UploadFile from '@/components/Upload/file'
  import UploadList from '@/components/UploadList'

  export default {
    name: 'user',
    components: {
      BasicForm,
      CustomCard,
      UploadFile,
      UploadList
    },
    data() {
      return {
        loading: false,
        isUpdate: false,
        baseUrl: process.env.BASE_FILE_URL,
        showCertProductsList: true,
        detail: {
          pdsCertProductsList: [],
          pdsCertFileList: [],
          pdsCertReportsDTOList: []
        },
        basicForm: [
          {
            label: '证书项目号',
            unit: '',
            element: 'input',
            name: 'certProjectNo',
            type: '',
            isRequired: true
          }, {
            label: '证书编号',
            unit: '',
            element: 'input',
            name: 'certNo',
            type: '',
            isRequired: true
          }, {
            label: '证书种类',
            element: 'select',
            name: 'certCategoryId',
            value: 'id',
            labelName: 'name',
            isRequired: true
          }, {
            label: '认证地区',
            unit: '',
            element: 'select',
            name: 'certArea',
            type: '',
            isRequired: true
          }, {
            label: '认证机构',
            unit: '',
            element: 'input',
            name: 'certOrg',
            type: '',
            isRequired: true
          }, {
            label: '生产厂家',
            unit: '',
            element: 'input',
            name: 'certManufacturer',
            type: '',
            isRequired: true
          }, {
            label: '持证单位',
            unit: '',
            element: 'select',
            name: 'certLicensedUnitId',
            type: '',
            value: 'id',
            labelName: 'name',
            isRequired: true
          }, {
            label: '证书有效期',
            unit: '',
            element: 'datePicker',
            name: 'certEffectiveDate',
            type: ''
          }, {
            label: '预警阈值',
            unit: '',
            element: 'input',
            name: 'warningDay',
            type: 'number'
          }
        ],
        proNo: null,
        proNoList: [],
        standard: null,
        standardList: [],
        reportForm: {},
        cdfList: [],
        reportDialog: false,
        cdfDialog: false,
        cdfForm: {}
      }
    },
    created() {
      this.getDict()
    },
     activated() {
       this.refresh()
     },
    computed: {
      ...mapGetters([
        'elements',
        'language'
      ])
    },
    methods: {
      /* 页面刷新初始化 */
      refresh() {
        if (this.$route.query.id) { /* 编辑 */
          this.isUpdate = this.$route.query.update || false;
          this.getDetail();
          /* 清空表单验证状态 */
          setTimeout(() => {
            this.$refs.basicForm.$refs.ruleForm.clearValidate();
          })
        } else { /* 添加 */
          this.detail = {
            pdsCertProductsList: [],
            pdsCertFileList: [],
            pdsCertReportsDTOList: []
          }
          setTimeout(() => {
            this.$refs.basicForm.$refs.ruleForm.clearValidate();
          })
        }
      },
      // 获取字典选项
      getDict() {
        /* 证书种类 */
        listApi.gories().then(res => {
          this.$set(this.basicForm[2], 'options', res.data);
          // this.basicForm[2].options = res.data;
        })
        /* 认证地区 */
        baseApi.getTypeValue('cert_area').then(res => {
          //this.basicForm[3].options = res.data.rows
           this.$set(this.basicForm[3], 'options', res.data.rows);
        })
        /* 持证单位 */
        prodApi.unitList().then(res => {
          //this.basicForm[6].options = res.data;
           this.$set(this.basicForm[6], 'options', res.data);
        })
        /* 项目编号 */
        listApi.getProjectNos().then(res => {
          this.proNoList = res.data;
        })
        certApi.getStandards().then(res => {
          this.standardList = res.data;
        })
      },
      selectChange(val) {
              let standard  = this.standardList.filter(item => {
              if (item.id == val) {
                return item
              }     
            });
          this.reportForm.certStandard = standard[0].name
      },
      /* 获取详情 */
      getDetail() {
        listApi.getCertDetail(this.$route.query.id).then(res => {
          if (res.code == 200) {
            this.detail = res.data.pdsCert;
            this.detail.pdsCertFileList = res.data.pdsCertFileList;
            this.detail.pdsCertReportsDTOList = res.data.pdsCertReportsDTOList;
            this.$set(this.detail, 'warningDay',JSON.stringify(res.data.pdsCert.warningDay))
            listApi.getCertProducts({certId: this.detail.id}).then(res => {
              // this.detail.pdsCertProductsList = res.data;
              this.$set(this.detail, 'pdsCertProductsList', res.data)
            })
          }
          setTimeout(() => {
            this.$refs.basicForm.$refs.ruleForm.clearValidate();
          })
        })
      },

      /* 获取详情 */
      refreshSaveBack(res) {
          if (res.code == 200) {
            this.detail.id = res.data.id;
          }
          setTimeout(() => {
            this.$refs.basicForm.$refs.ruleForm.clearValidate();
          })
   
      },
      /* 添加包含产品 */
      selectPro(item) {
        const isSame = this.detail.pdsCertProductsList.filter(state => state.plmModelNo.toLowerCase().indexOf(item.plmModelNo.toLowerCase()) === 0);
        if (isSame.length) {
          this.$message('产品型号已存在');
          return;
        }
        // this.proNoList[index].disabled = true;
        // this.proNoList[index].index = index;
        this.detail.pdsCertProductsList.push(item);
      },
      /* 删除包含产品 */
      delProject(index, itemIndex) {
        this.detail.pdsCertProductsList.splice(index, 1);
        this.proNoList[itemIndex] && (this.proNoList[itemIndex].disabled = false);
      },
      /* 获取上传正式文档 */
      getFiles(file) {
        this.showCertProductsList = false;
        this.$set(this.detail, 'pdsCertFileList', file.slice(-1));
        setTimeout(() => {
          this.showCertProductsList = true;
        })
      },
      /* 下载文档 */
      downloadFile() {
        window.open(this.baseUrl + '/' + this.detail.pdsCertFileList[0].fileUrl)
      },
      /* 编辑报告 */
      editReport(index) {
        if (index == 'add') { /* 添加 */
          this.reportForm = {
            index: -1,
            certReportEffectiveDate: '',
            certReportNo: '',
            certStandardId: null,
            params: '',
            pdsCertReportFileList: [],
            remark: '',
            pdsCertCdfsDTOList: []
          }
        } else {
          this.reportForm = JSON.parse(JSON.stringify(this.detail.pdsCertReportsDTOList[index]));
          this.reportForm.index = index;
          console.log('asdasdsadas',this.reportForm)
        }
        this.reportDialog = true;
        setTimeout(() => {
          this.$refs.reportForm.clearValidate();
        })
      },
      /* 报告编辑完成 */
      confirmReport() {
        this.$refs.reportForm.validate(valid => {
          if (valid) {
            if (!this.reportForm.pdsCertReportFileList.length) {
              this.$message.info('请上传报告文档');
              return;
            }
            if (this.reportForm.index !== -1) { /* 编辑 */
              this.$set(this.detail.pdsCertReportsDTOList, this.reportForm.index, this.reportForm)
              console.log('ytytytytyt',this.detail.pdsCertReportsDTOList)
            } else { /* 添加 */
              this.detail.pdsCertReportsDTOList.push(this.reportForm);
            }
            this.reportDialog = false;
          } else {
            this.$message.info('请将必填项填写完整')
            return;
          }
        })
      },
      /* 删除报告 */
      delReport(index) {
        this.detail.pdsCertReportsDTOList.splice(index, 1)
      },
      /* 编辑CDF */
      editCdf(index) {
        if (index == 'add') { /* 添加 */
          this.cdfForm = {
            index: -1,
            pdsCertCdfFilesList: [],
            remark: ''
          }
        } else {
          this.cdfForm = JSON.parse(JSON.stringify(this.reportForm.pdsCertCdfsDTOList[index]));
          this.cdfForm.index = index;
        }
        this.cdfDialog = true;
      },
      /* cdf编辑完成 */
      confirmCdf() {
        if (!this.cdfForm.pdsCertCdfFilesList.length) {
          this.$message.info('请上传文档');
          return;
        }
        if (this.cdfForm.index !== -1) { /* 编辑 */
          this.$set(this.reportForm.pdsCertCdfsDTOList, this.cdfForm.index, this.cdfForm)
        } else { /* 添加 */
          this.reportForm.pdsCertCdfsDTOList.push(this.cdfForm);
        }
        this.cdfDialog = false;
      },
      /* 删除CDF */
      delCdf(index) {
        this.reportForm.pdsCertCdfsDTOList.splice(index, 1)
      },
      /* 模糊查询 */
      _searchProNo(value, cb) {
        listApi.getProjectNos().then(res => {
          this.proNoList = res.data;
        })
        const results = value ? this.proNoList.filter(state => state.plmModelNo.toLowerCase().indexOf(value.toLowerCase()) === 0) : this.proNoList;
        results.forEach(item => item.value = item.plmModelNo);
        cb(results)

      },
      validateForm(type) {
        this.detail.newVersion = type && (!this.detail.status || this.isUpdate) ? true : false;
        if (type) { /* 提交 */
          this.detail.certStatus = 0
          this.detail.status = 2
          this.$refs.basicForm.submitForm().then(valid => {
            console.log('valid',valid)
            if (valid) {
              /* 包含产品 */
              if (!this.detail.pdsCertProductsList.length) {
                this.$message.info('请选择包含产品');
                return;
              } else {
                let flag = true;
                this.detail.pdsCertProductsList.map(item => {
                if (!item.id) {
                    flag = false;
                  }
                })
                if (!flag) {
                  this.$message.info('请选择包含产品的使用标准')
                  return;
                }
              }
              /* 证书文档 */
              if (!this.detail.pdsCertFileList.length) {
                this.$message.info('请上传证书文档');
                return;
              }
              /* 报告 */
              if (!this.detail.pdsCertReportsDTOList.length) {
                this.$message.info('请填写报告');
                return;
              }
              this.detail.status = type;
              this.submitForm()
            } else {
              this.$message.info('请将基本信息填写完整');
              return;
            }
          })
        } else { /* 草稿 */
          this.detail.certStatus = 0
          this.detail.status = 0
          if (!this.detail.certProjectNo) {
            this.$message.info('请填写正数项目号');
            return;
          }
          //this.detail.status = type;
          this.submitForm()
        }
      },
      submitForm() {
        this.loading = true;
        console.log('tytytytyt',this.detail)
        const postParams = JSON.parse(JSON.stringify(this.detail));
        postParams.pdsCertFileList.map((item, index) => {
          const newItem = {
            // certId: item.certId || null,
            fileId: item.id,
            // id: item.id || null,
            remark: item.remark || ''
          }
          postParams.pdsCertFileList[index] = newItem;
        })
        postParams.pdsCertReportsDTOList.map((item, index) => {
          item.pdsCertReportFileList.map((reportItem, reportIndex) => {
            const newItem = {
              fileId: reportItem.id
            }
            postParams.pdsCertReportsDTOList[index].pdsCertReportFileList[reportIndex] = newItem;
          })
          item.pdsCertCdfsDTOList.map((cdfItem, cdfIndex) => {
            cdfItem.pdsCertCdfFilesList.map((cdfFileItem, cdfFileIndex) => {
              const newItem = {
                fileId: cdfFileItem.id
              }
              postParams.pdsCertReportsDTOList[index].pdsCertCdfsDTOList[cdfIndex].pdsCertCdfFilesList[cdfFileIndex] = newItem;
            })
          })
        })
        console.log(postParams);
        listApi.saveCert(postParams).then(res => {
          if (res.code === 200) {
            this.$message.success((postParams.status ? '提交' : '保存草稿') + '成功')
            this.refreshSaveBack(res)
            this.$store.commit('ADD_LIST_REFRESH', this.$route.path.slice(0, this.$route.path.lastIndexOf('/')));
            if (postParams.status) {
              this.$store.dispatch('delActiveViews');
            }
          } else {
            this.$message.warning((postParams.status ? '提交' : '保存草稿') + '失败')
          }
          this.loading = false;
        }).catch(err => {
          console.log(err);
          this.loading = false;
        })
      }
    }
  }
</script>
